package org.minos.edit.model
{
	import flash.filesystem.File;
	import org.minos.edit.controller.manager.FileManager;
	import org.minos.edit.EditFacate;
	import org.minos.edit.model.vo.AssetsVO;
	import org.minos.edit.model.vo.DialogVO;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	/**
	 * ...
	 * 资源代理
	 * @author Minos
	 */
	public class AssetsProxy extends Proxy
	{
		//
		public static const NAME : String = "AssetsProxy";
		//类型
		public static const SOUND : String = NAME + "_Sound";
		public static const MOVIE : String = NAME + "_Movie";
		public static const SWF : String = NAME + "_Swf";
		//资源文件夹名
		public static const FILE_NAME : String = "assets";
		
		private var resType : Array = [ ".swf" , ".mp3" ];
		
		/**
		 * 构造
		 * @param	data
		 */
		public function AssetsProxy( data : Object = null )
		{
			super( NAME , data );
		}
		
		/**
		 * 获取资源列表
		 * @param	_file
		 */
		public function getAssets( _file : File = null ) : void
		{
			var file : File = checkAssets( _file );
			if ( file == null )
				return;
			var files : Array = getDirFiles( file );
			var list : Array = [];
			for each ( var i : File in files )
			{
				var obj : AssetsVO = new AssetsVO();
				obj.label = i.name;
				obj.url = FILE_NAME + "/" + file.getRelativePath( i , true );
				list.push( obj );
			}
			
			setData( list );
			FileManager.setRootFile( file );
			
		}
		
		/**
		 * 检查是否有资源文件夹
		 * @param	_file
		 * @return
		 */
		private function checkAssets( _file : File ) : File
		{
			if ( _file == null )
				return null;
				
			var _files : Array = _file.getDirectoryListing();
			for each ( var j : File in _files )
			{
				if ( j && j.name == AssetsProxy.FILE_NAME )
				{
					return j;
				}
			}
			//error
			var dialog : DialogVO = new DialogVO( "错误" , "没找到资源文件夹！\n [ assets/.. ]" );
			sendNotification( EditFacate.SHOW_DIALOG , dialog );
			return null;
		}
		
		/**
		 * 筛选
		 * @param	dir
		 * @return
		 */
		private function getDirFiles( dir : File ) : Array
		{
			var arr : Array = [];
			var dirFiles : Array = dir.getDirectoryListing();
			var file : File;
			
			for ( var i : int = 0 ; i < dirFiles.length ; i++ )
			{
				file = dirFiles[ i ];
				if ( file.isDirectory )
				{
					arr = arr.concat( getDirFiles( file ) );
					continue;
				}
				if ( isResFile( file ) )
				{
					arr.push( file );
				}
			}
			return arr;
		}
		
		/**
		 * 筛选
		 * @param	file
		 * @return
		 */
		private function isResFile( file : File ) : Boolean
		{
			for ( var i : uint = 0 ; i < resType.length ; i++ )
			{
				if ( file.name.toLowerCase().indexOf( resType[ i ] ) != -1 )
				{
					return true;
				}
			}
			return false;
		}
	
	}

}